package com.huanxin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huanxin.param.CallData;
import com.huanxin.param.DeviceAlarmCallParam;
import com.huanxin.param.HuanXinAiBotAccessToken;
import com.huanxin.param.HuanXinImportMobileRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class HuanXinTest {

    public static final String urlTest ="www.aigcyun.cn/paas4x2";
    public static final String TOKEN ="21314411589645436842434015236216";
    public static final Integer taskId =116832588;
  public static final String PHONE_NUMBER ="18616972562";
  // public static final String PHONE_NUMBER ="18684917101";
    public static void main(String[] args) {
        getToken();
        DeviceAlarmCallParam callParam = new DeviceAlarmCallParam();
        callParam.setLicensePlate("沪EG5627");
        callParam.setAlarmMsg("您所驾驶的 沪 A A 8 8 7 挂 的轮位 一轴左外 已触发严重胎温高报警,温度报警：请立刻在应急车道停车，检查全车刹车鼓温度");
        callParam.setOrderNo(8887777);
        callParam.setMobile(PHONE_NUMBER);
       // alarmCall(callParam);
    }


    public static void getToken() {
        Map<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("clientId", "2f0986a3-f14e-4ebc-9ff7-2deca20fc8da");
        dataMap.put("clientScr", "5923df06-cb00-4b05-b504-df63d25a7e39");
        HttpResponse response = post(dataMap, "/accreditation");

        // 打印curl命令
        printCurlCommand(dataMap, "http://www.vsbot.cn/paas4x2/accreditation");
        JSONObject jsonObject = JSONObject.parseObject(response.body());
        HuanXinAiBotAccessToken targethuanXinAiBotAccessToken = new HuanXinAiBotAccessToken()
                .setToken(jsonObject.getString("message")).setExpireTime(jsonObject.getString("expireTime"));
        System.out.println(JSON.toJSONString(jsonObject));
    }


    public static HttpResponse post(Map<String, Object> dataMap, String api) {
        Map<String, String> headers = new HashMap<>(2);
        headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json;charset=utf-8");
        String postData = JSONUtil.toJsonStr(dataMap);

        printCurlCommand(urlTest+"/importMobile",headers,postData);
        return HttpUtil.createPost(urlTest
                + api).addHeaders(headers).body(postData).execute();
    }

    public static void printCurlCommand(Map<String, Object> dataMap, String url) {

        String postData = JSON.toJSONString(dataMap);

        StringBuilder curlCommand = new StringBuilder();
        curlCommand.append("curl -X POST ");
        curlCommand.append("\"").append(url).append("\" ");
        curlCommand.append("-H \"Accept: application/json\" ");
        curlCommand.append("-H \"Content-Type: application/json;charset=utf-8\" ");
        curlCommand.append("-d '").append(postData).append("'");

        System.out.println(curlCommand.toString());
    }


    public static void alarmCall(DeviceAlarmCallParam param) {
        // 判断10分钟内是否告警过


        CallData callData = new CallData();
        callData.setMobile(param.getMobile());
        callData.setExtData(StrUtil.format("$号码={}&$车牌={}&报警={}&$huanXinCallBackRecordId={}&$orderType={}&$orderNo={}&$mobilesSecond={}", param.getMobile(),
                param.getLicensePlate(), param.getAlarmMsg(), taskId, 1,param.getOrderNo(),"17355637361"));
        HuanXinImportMobileRequest request = new HuanXinImportMobileRequest();
        request.setAccessToken(TOKEN);
        request.setJobName("测试");
        request.setCallData(Collections.singletonList(callData));
        request.setJobUserStatus("startup");
        request.setBatchUserStatus("startup");
        callServicer(param.getOrderNo(), request);
    }

    public static void callServicer(Integer orderNo, HuanXinImportMobileRequest request) {
        // 此次任务Id

        String taskName = "测试";
        try {
            // 内部任务名称
            taskName = adAiBotCallJob(taskId, request);
        } catch (Exception e) {
            log.error(StrUtil.format("创建环信Ai机器人外呼失败：{}", ExceptionUtil.stacktraceToOneLineString(e)), e);
        }

    }


    public static String adAiBotCallJob(Integer taskId, HuanXinImportMobileRequest request) {
        if (Validator.isEmpty(request.getAccessToken())) {
            throw new ValidateException("创建环信Ai机器人外呼失败：未获取到环信token");
        }

        // 导入号码
        HttpResponse response = post(BeanUtil.beanToMap(request), "/importMobile");
        System.out.println("结果: "+JSON.toJSONString(response));
        return StrUtil.format("{}{}", request.getJobName(), taskId);
    }
    public static void printCurlCommand(String url, Map<String, String> headers, String postData) {
        StringBuilder curlCommand = new StringBuilder();
        curlCommand.append("curl -X POST ");
        curlCommand.append("\"").append(url).append("\" ");

        for (Map.Entry<String, String> header : headers.entrySet()) {
            curlCommand.append("-H \"").append(header.getKey()).append(": ").append(header.getValue()).append("\" ");
        }

        curlCommand.append("-d '").append(postData).append("'");

        System.out.println(curlCommand.toString());
    }
}
